package problems.solved;

import java.util.List;

import problems.Problem;

import utils.Utils;

public class Problem37 extends Problem<Integer> {
	public static void main(String[] args) {
		Problem37 problem37 = new Problem37();
		problem37.runTimed();
		problem37.printResult();
	}

	@Override
	public void run() {
		List<Integer> sieve = Utils.sieve(20000000);
		int found = 0;
		int sum = 0;
		for (int prime : sieve) {
			if (isTruncatable(prime)) {
				sum += prime;
				System.out.println("Found " + prime);
				if (++found == 11) {
					setResult(sum);
					return;
				}
			}
		}
	}

	private boolean isTruncatable(int prime) {
		String string = Integer.toString(prime);
		if (string.length() == 1) {
			return false;
		}
		for (int i = 1; i < string.length(); i++) {
			if (! (check(string.substring(i)) && 
					check(string.substring(0, string.length() - i)))) {
				return false;
			}
		}
		return true;
	}

	private boolean check(String substring) {
//		System.out.println(substring);
		return Utils.isPrimeCached(Long.parseLong(substring));
	}
}
